package com.l024.easysecurity.modules.sys.controller.sys;

import com.alibaba.fastjson.JSONObject;
import com.l024.easysecurity.common.page.PageData;
import com.l024.easysecurity.common.page.PageParams;
import com.l024.easysecurity.common.utils.R;
import com.l024.easysecurity.modules.sys.entity.SysMenu;
import com.l024.easysecurity.modules.sys.entity.SysUser;
import com.l024.easysecurity.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/user")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    /**
     * 获取用户下的所有菜单权限
     * @param userId
     * @param rsp
     * @return
     */
    @GetMapping("/menu/{userId}")
    public R getUserMenus(@PathVariable("userId")long userId, HttpServletResponse rsp){
//        rsp.addHeader("test","test");//自定义header头
//        rsp.addHeader("Access-Control-Expose-Headers","test");//申明客户端可以访问
        List<SysMenu> userAllMenus = sysUserService.getUserAllMenus(userId);
        return new R().put("data",userAllMenus);
    }

    /**
     * 分页条件查询
     */
    @PostMapping("/list")
    public R list(@RequestBody JSONObject param){
        int pageSize = 10;
        int pageNum = 1;
        SysUser sysUser = new SysUser();
        if(param!=null){
            if(param.containsKey("pageSize")){
                pageSize = param.getInteger("pageSize");
            }
            if(param.containsKey("pageNum")){
                pageNum = param.getInteger("pageNum");
            }

            if(param.containsKey("user")){
                JSONObject user = param.getJSONObject("user");
                if(user!=null){
                    sysUser = JSONObject.toJavaObject(user,SysUser.class);
                }
            }
        }
        PageData<SysUser> sysUserPageData = sysUserService.selectPageSysUser(sysUser, PageParams.build(pageSize, pageNum));
        return new R().put("data",sysUserPageData);
    }

    /**
     * 添加用户
     */
    @PostMapping("/add")
    public R addUser(@RequestBody SysUser sysUser){
        if(sysUser!=null){
            return sysUserService.addUser(sysUser);
        }
        return R.error("添加数据为null");
    }

    /**
     * 添加用户
     */
    @PostMapping("/update")
    public R updateUser(@RequestBody SysUser sysUser){
        if(sysUser!=null){
            return sysUserService.updateUser(sysUser);
        }
        return R.error("更新数据为null");
    }

    /**
     * 删除用户
     */
    @GetMapping("/del/{userId}")
    public R delSysUser(@PathVariable("userId")long userId){
        return sysUserService.delSysUser(userId);
    }
}
